package com.algorithm;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

@Slf4j
public class OrderShardingAlgorithm implements PreciseShardingAlgorithm<String> {

    /**
     * 实际数据库/表的模板.
     */
    private static final String ACTUAL_TARGET_TEMPLATE = "%s_%d";
    Integer DATABASE_NUM = 2;
    Integer TABLE_NUM = 2;




    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> shardingValue) {
        log.info("availableTargetNames: {}", JSON.toJSONString(availableTargetNames));
        log.info("PreciseShardingValue(logicTableName={}, columnName={},, value={})", shardingValue.getLogicTableName(), shardingValue.getColumnName(), shardingValue.getValue());

        if (availableTargetNames.stream().findFirst().get().startsWith(shardingValue.getLogicTableName())) {
            // 表路由匹配
            int tableIndex = ShardingDbUtil.getActualTableIndex(shardingValue.getValue(), TABLE_NUM);
            String targetNode = String.format(ACTUAL_TARGET_TEMPLATE, shardingValue.getLogicTableName(), tableIndex);
            log.info("sharding table: {}", targetNode);
            return targetNode;
        } else {
            // 库路由匹配
            long databaseIndex = ShardingDbUtil.getActualTableIndex(shardingValue.getValue(), DATABASE_NUM);
            String targetNode = String
                    .format(ACTUAL_TARGET_TEMPLATE, "ds", databaseIndex);
            log.info("sharding database: {}", targetNode);
            return targetNode;
        }
    }


}
